package com.chenhy.server.config;

import com.chenhy.server.utils.JwtTokenUtil;
import lombok.experimental.Accessors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Value("$" +
            "{jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserDetailsService userDetailsService;

    // 添加端点，在网页中可以通过websocket连接
    // 也就是我们配置websocket的服务地址，并且可以指定是否使用socketJS
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // 1.将ws/ep路径注册为stomp的端点，用户连接了这个端点就可以进行websocket通信，支持socketJS
        // 2.允许跨域
        // 3.使用socketJS进行连接，支持socketJS访问
        registry.addEndpoint("/ws/ep").setAllowedOrigins("*").withSockJS();
    }

    // 输入通道参数配置
    // 因为使用了jwt，所以需要进行token处理登录
    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(new ChannelInterceptor() {
            @Override
            public Message<?> preSend(Message<?> message, MessageChannel channel) {
                StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
                // 判断是否是连接，如果是，需要获取Token,并且设置用户对象
                if (StompCommand.CONNECT.equals(accessor.getCommand())){
                    // 拿到前端发送时请求头中key为Auth-Token的值
                    String token = accessor.getFirstNativeHeader("Auth-Token");
                    if (!StringUtils.isEmpty(token)){
                        // 截取有效token
                        System.out.println(token);
                        System.out.println(tokenHead);
                        String authToken = token.substring(tokenHead.length());
                        System.out.println(authToken);
                        String username = jwtTokenUtil.getUserNameFromToken(authToken);
                        // 如果token存在用户名
                        if (!StringUtils.isEmpty(username)){
                            // 登录
                            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                            // 判断token是否有效
                            if (jwtTokenUtil.validateToken(authToken, userDetails)){
                                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                                accessor.setUser(authenticationToken);
                            }
                        }
                    }
                }
                return message;
            }
        });
    }

    // 配置消息代理
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        // 配置代理域，可配置多个，目的是配置代理目的地的前缀为/queue，可以在配置域上向客户推送消息，
        // 相当于消息队列里面的queue队列，前端订阅后可从服务端推送消息给前端
        registry.enableSimpleBroker("/queue");
    }
}
